package com.qf.InternetProgram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class A {
	public static void main(String[] args) {
		sendMessageBySocket();
		//程序A
	}

	public static void sendMessageBySocket() {
		
		
		try {
			
			
			//3.请求与B建立连接
			//Socket socket = new Socket("192.168.231.103",8090);
			Socket socket = new Socket("192.168.164.1",11112);
			//Socket socket = new Socket("192.168.51.14",8090);
			//Socket socket = new Socket("192.168.51.13",8888);
			System.out.println("【A1】与B连接成功...");
			
			//可以发消息
			OutputStream os = socket.getOutputStream();
			//可以接收消息
			InputStream is = socket.getInputStream();
			
			
			//字节流转化为字符流
			//BufferedReader是什么？？
			
			//将字节输入流转换成字符输入流
			InputStreamReader charStream = new InputStreamReader(is);
			
			BufferedReader br = new BufferedReader(charStream);
			
			PrintWriter pw = new PrintWriter(os);
			
			Scanner sc = new Scanner(System.in);
			
			
			
//			Date d =new Date();
//			
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//			String date = sdf.format(d);
			String message;
			String endSign ="";
			do {
				//4.程序A控制台扫描一句话发送给B
				System.out.println("【A2】请输入一句话给服务器：");
				message = sc.nextLine();
				
				pw.println(message);
				
				//pw.println(date);
				
				pw.flush();
				
				//socket.shutdownInput();
				//7.程序A接收程序B的回复
//				socket.getInputStream();
				message= br.readLine();
				System.out.println("【A3】回复B程序给A程序回复的消息："+message);
				//socket.shutdownInput();
				//socket.close();
				System.out.println("【A】会话是否还需要继续？");
				
			}while(!(message.equals("bye")));
				
				
			
			
			/*
			 * 这里会报错，原因是B程序使用accept后会导致通讯阻塞，需要使用socket.close方法关闭
			 * 具体看网上的办法把
			 * */
			
			
		}catch(SocketTimeoutException e) {
			
			System.out.println("Socket连接超时...");
			e.printStackTrace();
			
			
		}
		catch(SocketException e) {
			System.out.println("Socket连接出现异常...");
			
			e.printStackTrace();
			
		}
		
		catch(IOException e) {
			
			System.out.println("IO流数据交换时发生异常...");
			e.printStackTrace();
		}
		
		
	}
}
